#!/bin/bash


if [ $# -lt 1 ]; then
    echo "$0 <barnch> [remote branch]"
    exit 1
fi

REMOTE=coding
BRANCH=${1}
RBRANCH=${2:-$BRANCH}
BATCH_SIZE=1000

# check if the branch exists on the remote
# if git show-ref --quiet --verify refs/remotes/$REMOTE/$BRANCH; then
#     # if so, only push the commits that are not on the remote already
#     range=$REMOTE/$BRANCH..HEAD
# else
#     # else push all the commits
#     range=HEAD
# fi

range=HEAD

echo "Range: $range"

# count the number of commits to push
n=$(git log --first-parent --format=format:x $range | wc -l)

echo "Commits to push: $n"

count=$(echo "$n/${BATCH_SIZE}" | bc)
current=1
# push each batch
for i in $(seq $n -$BATCH_SIZE 1); do
    # get the hash of the commit to push
    h=$(git log --first-parent --reverse --format=format:%H --skip $i -n1)
    echo
    echo "Pushing $h ... [${current}/${count}]"
    echo
    git push $REMOTE $h:refs/heads/$RBRANCH
    current=$((current + 1))
done

echo "Final push ..."
# push the final partial batch
git push $REMOTE HEAD:refs/heads/$RBRANCH

echo "Done"
